#include<iostream>
using namespace std;
int n, H, M;
int main()
{
	int t;
	cin >> t;
	while (t--) {
		cin >> n >> H >> M;
		int ans = H * 60 + M;
		int res = 1e9;
		while (n--) {
			int h, m;
			cin >> h >> m;
			int time_1 = h * 60 + m - ans;
			if (time_1 < 0)time_1 = 24 * 60 - ans + h * 60 + m;
			res = min(res, time_1);
		}
		cout << res / 60 << " " << res % 60 << endl;
	}
	return 0;
}